package com.langyiquan.service.impl;

import com.langyiquan.exception.http.ParamException;
import com.langyiquan.service.ResourceService;
import org.apache.commons.io.IOUtils;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class DiskResourceImpl implements ResourceService {

    @Autowired
    private Environment env;

    @Autowired
    private Sid sid;

    @Override
    public String uploadFile(MultipartFile file, String category) {

        String fileSpace = env.getProperty("resource.upload-location");

        String uploadPathPrefix = File.separator + category + File.separator;

        if(file != null){

            FileOutputStream fileOutputStream = null;

            String fileName = file.getOriginalFilename();

            String fileNameArr[] = fileName.split("\\.");

            String suffix = fileNameArr[fileNameArr.length - 1];

            if(!suffix.equalsIgnoreCase("png") && !suffix.equalsIgnoreCase("jpg") && !suffix.equalsIgnoreCase("jpeg") && !suffix.equalsIgnoreCase("gif")){
                throw new ParamException(1006);
            }

            String newFileName = sid.nextShort() + "." + suffix;

            // 上传的头像最终保存的位置
            String finalFacePath = fileSpace + uploadPathPrefix + File.separator + newFileName;
            uploadPathPrefix += ("/"+newFileName);

            File outFile = new File(finalFacePath);
            if (outFile.getParentFile() != null) {
                // 创建文件夹
                outFile.getParentFile().mkdirs();
            }

            // 文件输出保存到目录
            try {
                fileOutputStream = new FileOutputStream(outFile);
                InputStream inputStream = file.getInputStream();
                IOUtils.copy(inputStream, fileOutputStream);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fileOutputStream != null) {
                        fileOutputStream.flush();
                        fileOutputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            String imageServerUrl = env.getProperty("resource.server-url");

            return imageServerUrl+uploadPathPrefix;
        }else{
            throw new ParamException(1007);
        }

    }
}
